#@+leo-ver=4-thin
#@+node:ville.20090720134348.1836:@thin shortcuts.py
import sys,os
import itpl
import stringlist
from contextlib import contextmanager


#@+others
#@+node:ville.20090720134348.1837:shell command helpers
def var_expand(cmd,depth=0):
    """Expand python variables in a string.

    The depth argument indicates how many frames above the caller should
    be walked to look for the local namespace where to expand variables.

    The global namespace for expansion is always the user's interactive
    namespace.
    """

    return str(itpl.ItplNS(cmd,                      
                      # Skip our own frame in searching for locals:
                      sys._getframe(depth+1).f_locals # locals
                      ))


def shcap(cmd):
    """ Execute shell command, capture output to string list """

    fullcmd = var_expand(cmd, depth=1)
    sl = stringlist.shcmd(fullcmd)
    return sl

def shrun(cmd):
    fullcmd = var_expand(cmd, depth=1)
    os.system(fullcmd)

@contextmanager
def chdir(new):
    #print('chdir\'ing to %s' % new)
    old = os.getcwd()
    new_exp = var_expand(new, depth = 2)
    path_final = os.path.abspath(os.path.expanduser(os.path.normcase(new_exp)))

    os.chdir(path_final)
    try:
        yield path_final
    finally:
        os.chdir(old)


#@-node:ville.20090720134348.1837:shell command helpers
#@-others
#@nonl
#@-node:ville.20090720134348.1836:@thin shortcuts.py
#@-leo
